package net.qiqb.module.spring;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ReflectUtil;
import net.qiqb.module.ModuleContext;
import net.qiqb.module.ModuleServiceConfig;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;

public class ModuleApiProxyHandler implements InvocationHandler {

    private final Class<?> type;

    private Object target;

    private ModuleContext moduleContext;

    public ModuleApiProxyHandler(Class<?> type, ModuleContext moduleContext) {
        this.type = type;
        this.moduleContext = moduleContext;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 这里可以添加前置和后置处理逻辑
        // 例如权限检查、日志记录等
        if (target == null) {
            // 尝试从
            final ModuleServiceConfig serviceConfig = moduleContext.getServiceConfig(type.getName());
            if (serviceConfig == null) {
                //
                throw new IllegalStateException("获取不到代理到目标对象");
            }
            this.target = serviceConfig.getTarget();
        }
        if (target != null) {
            try {

                final Object invoke = ReflectUtil.invoke(target, method, args);
                return invoke;
            }catch (Exception e){
                ExceptionUtil.wrapAndThrow(ExceptionUtil.getRootCause(e));
            }
        }
        throw new IllegalStateException("模块接口代理对象获取不到实际操作的对象:" + type.getName());
    }

    public void setTarget(Object target) {
        this.target = target;
    }
}